package supertuxwar.powerup;

import net.phys2d.raw.Body;
import net.phys2d.raw.CollisionEvent;
import net.phys2d.raw.World;
import net.phys2d.raw.shapes.Box;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

import supertuxwar.AbstractEntity;
import supertuxwar.Actor;
import supertuxwar.TileEnvironment;

public abstract class Powerup extends AbstractEntity {
	
	/** The world to which the Powerup has been added */
	protected World world;
	
	protected Actor actor;
	
	public Powerup(float x, float y) {
		body = new Body(new Box(64,64), 0.1f);
		body.setUserData(this);
		body.setPosition(x,y);
		body.setFriction(0.1f);
	}

	public abstract void doAction() throws SlickException;
	public abstract Image getImage();
	
	public void setActor(Actor actor) {
		this.actor = actor;
	}
	
	public Actor getActor() {
		return actor;
	}
	
	@Override
	public void setWorld(World world) {
		this.world = world;
	}
	
	@Override
	public Body getBody() {
		return body;
	}
	
	@Override
	public void render(Graphics g) {
		// 尚未被actor获取
		if(actor == null) {
			g.translate(getX(), getY());
			g.rotate(0,0,(float) Math.toDegrees(body.getRotation()));
			int width = getImage().getWidth();
			int height = getImage().getHeight();
			getImage().draw(-width/2,-height/2,width,height);
			g.rotate(0,0,(float) -Math.toDegrees(body.getRotation()));
			g.translate(-getX(), -getY());
		}
	}
	

	@Override
	public void update(int delta) {

		if (world == null) {
			return;
		}
		
		// loop through the collision events that have occured in the
		// world
		CollisionEvent[] events = world.getContacts(body);
		
		for (int i=0;i<events.length;i++) {
			
			if(events[i].getBodyA() == body) {
				Object obj = events[i].getBodyB().getUserData();
				if(obj instanceof Actor) {
					Actor actor = (Actor)obj;
					actor.setPowerup(this);
					setActor(actor);
					
					TileEnvironment.getInstance().removeEntity(this);
				}
			} else {
				Object obj = events[i].getBodyA().getUserData();
				if(obj instanceof Actor) {
					Actor actor = (Actor)obj;
					actor.setPowerup(this);
					setActor(actor);
					
					TileEnvironment.getInstance().removeEntity(this);
				}
			}
		}
	}
	
	@Override
	public void preUpdate(int delta) {
		
	}
}
